package no.group.gowther.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import no.group.gowther.enums.FileType;
import no.group.gowther.service.dto.FileDTO;
import org.springframework.lang.Nullable;

import java.nio.file.Paths;

/**
 * @author ayatsuji
 * @date 2022-04-20 23:37
 * @since
 */
public class JsonUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        OBJECT_MAPPER.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
    }

    public static JsonNode toJsonNode(String json) throws JsonProcessingException {
        return OBJECT_MAPPER.readTree(json);
    }

    public static <T> T toPOJO(String json, Class<T> clz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, clz);
    }

    public static String pojoToString(Object pojo) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(pojo);
    }

    @Nullable
    public static JsonNode findByPath(JsonNode node, String pathPattern) {
        final String[] paths = pathPattern.split("\\.");
        for (String path: paths) {
            node = node.findValue(path);
            if (node == null) return null;
        }
        return node;
    }

    public static void main(String[] args) throws JsonProcessingException {
        FileDTO fileDTO = new FileDTO();
        fileDTO.setFile(Paths.get("E:/2023德国公开赛签表.jpg"));
        fileDTO.setType(FileType.IMAGE);
        String s1 = JsonUtils.pojoToString(fileDTO);
        System.out.println(s1);
    }
}
